var updateStatus = function(complete, replays_processed) {
  $('#status').text((complete ? 'Complete' : 'Running') + ', ' + replays_processed + ' replays processed');
};

var updateResults = function(results) {
  var li = $('#results');
  li.empty();
  for (var i = 0; i < results.length; ++i) {
    li.append($('<li>' + results[i].target + ': ' + results[i].result + '</li>'));
  }
};

var onParseReplaysResponse = function(data) {
  updateStatus(false, 0);
  getBatchTaskStatus(data['batch_task_key'], 0);
};

var onGetBatchTaskStatusResponse = function(batch_task_key, last_value, data) {
  updateStatus(data.task_status.complete, data.task_status.entities_processed);
  updateResults(data.task_results);
  if (!data.task_status.complete || data.task_status.entities_processed != last_value) {
    setTimeout(function() { getBatchTaskStatus(batch_task_key, data.task_status.entities_processed); }, 5000);
  }
};

var getBatchTaskStatus = function(batch_task_key, last_value) {
  $.ajax({
    url: '/api/getBatchTaskStatus',
    data: { 'batch_task_key': batch_task_key },
    dataType: 'json',
    success: function(data) { onGetBatchTaskStatusResponse(batch_task_key, last_value, data); },
  });
};

$(document).ready(function() {
  $('#container').append($('<div id="status"></div>'));
  $('#container').append($('<ul id="results"></ul>'));
  $.ajax({
    url: '/api/parseReplays',
    dataType: 'json',
    success: onParseReplaysResponse,
  });
});
